package com.xiaobai.java_core.encrypt;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

/**
 * @Author 王天文
 * @Date 2024/12/9 8:22
 * @Description:
 */
@Slf4j
public class EncryptTest1 {

    @Test
    public void test() {
        try {
            // 生成密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(1024);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            // 创建加密对象
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            // 待加密数据
            String plaintext = "Hello, World!";
            byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
            String encryptDataStr = Base64.getEncoder().encodeToString(encryptedBytes);
            log.info("加密后的数据：{}", encryptDataStr);

            // 解密
            byte[] encryptDataBytes = Base64.getDecoder().decode(encryptDataStr);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedBytes = cipher.doFinal(encryptDataBytes);
            String decryptedText = new String(decryptedBytes);

            System.out.println("解密后的数据: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
